package com.example.score.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private static final Logger log = LoggerFactory.getLogger(WebConfig.class);

    @Value("${bsta.profile}")
    private String bstaProfile;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 在bsta.profile路径下创建upload和pdf目录
        String uploadDir = bstaProfile + File.separator + "upload";
        String pdfDir = bstaProfile + File.separator + "pdf";
        
        // 确保上传目录存在
        createDirectoryIfNotExists(uploadDir);
        createDirectoryIfNotExists(pdfDir);
        
        // 构建文件URL路径（注意：Windows路径需要额外处理）
        String uploadPath = "file:" + uploadDir + File.separator;
        String pdfPath = "file:" + pdfDir + File.separator;
        
        // 替换Windows路径分隔符
        uploadPath = uploadPath.replace("\\", "/");
        pdfPath = pdfPath.replace("\\", "/");
        
        log.info("配置静态资源映射 - upload路径: {}", uploadPath);
        log.info("配置静态资源映射 - pdf路径: {}", pdfPath);
        
        registry.addResourceHandler("/upload/**")
               .addResourceLocations(uploadPath, pdfPath);
    }
    
    private void createDirectoryIfNotExists(String dirPath) {
        File directory = new File(dirPath);
        if (!directory.exists()) {
            boolean created = directory.mkdirs();
            if (created) {
                log.info("创建目录成功: {}", directory.getAbsolutePath());
            } else {
                log.warn("创建目录失败: {}", directory.getAbsolutePath());
            }
        }
    }
}